/*
 *  Copyright 2020-2025 the original author or authors.
 *  You cannot use this file unless authorized by the author.
 */

package org.ipig.commons.helper;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * BeanHelper
 * 实现ApplicationContextAware,提供直接使用spring IOC容器中bean
 * <li>第一种方式【new方式创建】//@Bean public BeanHelper getBeanHelper() { return new BeanHelper();}</li>
 * <li>第二种方式【IOC容器创建对象】 &lt;bean class="cn.gov.zjport.skeleton.common.helper.BeanHelper"/></li>
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: BeanHelper.java 20 2020-05-20 03:46:11Z ts <comchnts@163.com> $$
 * @since 1.0
 */
public class BeanHelper implements ApplicationContextAware {
    /**
     * ApplicationContext
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (BeanHelper.applicationContext == null) {
            BeanHelper.applicationContext = applicationContext;
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}